<template>
    <view class="container">
        <view class="login-content">
            <view class="logo">
                <text class="iconfont icon-mood">&#xe603;</text>
            </view>
            <h1>心情盒子</h1>
            <p>记录每一天的情绪，了解自己</p>
            <button 
                class="login-btn" 
                open-type="getUserInfo" 
                @getuserinfo="handleLogin"
                :loading="isLoading"
            >
                微信一键登录
            </button>
        </view>
    </view>
</template>

<script>
import { mapActions } from 'vuex'

export default {
    data() {
        return {
            isLoading: false
        }
    },
    methods: {
        ...mapActions('user', ['wxLogin']),
        
        async handleLogin(e) {
            if (this.isLoading) return;
            this.isLoading = true;

            try {
                // 调用微信登录获取 code
                const [loginErr, loginRes] = await uni.login({
                    provider: 'weixin'
                });
                
                if (loginErr) {
                    throw new Error('微信登录失败');
                }

                // 获取用户信息
                const userInfo = e.detail.userInfo;
                
                if (!userInfo) {
                    throw new Error('获取用户信息失败，请授权后重试');
                }

                // 调用Vuex登录方法
                const result = await this.wxLogin({
                    code: loginRes.code,
                    userInfo: userInfo
                });
                
                console.log('登录成功', result);

                // 跳转到首页
                uni.switchTab({
                    url: '/pages/home/index'
                });
            } catch (error) {
                console.error('登录失败', error);
                uni.showToast({
                    title: error.message || '登录失败',
                    icon: 'none'
                });
            } finally {
                this.isLoading = false;
            }
        }
    }
}
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #F8F8F8;
}

.login-content {
    text-align: center;
    width: 80%;
    max-width: 320px;
}

.logo {
    width: 100px;
    height: 100px;
    background-color: #E6F4EA;
    border-radius: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 auto 24px;
}

.logo .iconfont {
    font-size: 48px;
    color: #1AAD19;
}

h1 {
    font-size: 24px;
    margin-bottom: 12px;
    color: #333;
}

p {
    color: #666;
    margin-bottom: 36px;
}

.login-btn {
    background-color: #1AAD19;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 32px;
    font-size: 16px;
    width: 100%;
    box-shadow: 0 4px 12px rgba(26, 173, 25, 0.2);
}

.login-btn:active {
    opacity: 0.8;
}
</style> 